# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'ks': {  # dwc 支付宝：100-5000
        'API_KEY': 'Auq2&ZDsw#Y$brSxngMfcD*iRjQV&Caj',
        'gateway': 'https://api.flyhongyi.com:22891/pay/index.html',
        'query_gateway': 'https://api.flyhongyi.com:22891/ordersearch.html',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# sign (签名 md5($merid +  $orderno + $paytype + $money + $notifyurl + $deviceip + $time + $key))
def gen_sign(d, key):
    s = '{}{}{}{}{}{}{}'.format(
        d['merid'], d['orderno'], d['paytype'], d['money'], d['notifyurl'], d['time'], key)
    return generate_sign(s)


# sign (签名 md5($merid + $orderno + $money + $merorderno + $time + $key))
def calc_sign(d, key):
    s = '{}{}{}{}{}{}'.format(
        d['merid'], d['orderno'], d['money'], d['merorderno'], d['time'], key)
    return generate_sign(s)


# sign (签名 md5(merid + orderno + time + key))
def query_sign(d, key):
    s = '{}{}{}{}'.format(d['merid'], d['orderno'], d['time'], key)
    return generate_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = calc_sign(params, key)
    if sign.lower() != calculated_sign.lower():
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return '1'
    return '1'


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_device_id(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_id') or 'IMEI00000001111112222222'


def _build_query_string(params):
    s = 'sign={}&merid={}&time={}&orderno={}'.format(
        params['sign'], params['merid'],
        params['time'], params['orderno'],
    )
    return s


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    parameter_dict = OrderedDict((
        ('merid', app_id),
        ('orderno', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('money', int(pay_amount * 100)),
        ('notifyurl', '{}/pay/api/{}/huifupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('deviceip', _get_device_ip(info)),
        ('deviceid', _get_device_id(info)),
        ('devicetype', '2'),
        ('payname', user_info.get('user_alicount') or ''),
        ('payrealname', user_info.get('user_alicount') or ''),
        ('time', int(time.time())),
        ('user_id', str(pay.user_id)),
        ('tel', user_info.get('tel') or ''),
    ))
    parameter_dict['sign'] = gen_sign(parameter_dict, api_key)
    _LOGGER.info("huifupay create: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("huifupay create charge data: %s %s", response.status_code, response.text)
    return {'charge_info': json.loads(response.text)['payurl']}


def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    data['merid'] = app_id
    api_key = _get_api_key(app_id)
    _LOGGER.info("huifupay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['merorderno']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['status'])
    trade_no = str(data['orderno'])
    total_fee = float(data['money']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == '1':
        _LOGGER.info('huifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    third_no = json.loads(pay_order.extend or '{}').get('trade_no', '')
    if not third_no:
        return
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('merid', app_id),
        ('orderno', str(third_no)),
        ('time', int(time.time()))
    ))
    parameter_dict['sign'] = query_sign(parameter_dict, api_key)
    _LOGGER.info("huifupay query  data: %s", json.dumps(parameter_dict))
    url = _get_query_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    response = requests.get(url)
    _LOGGER.info("huifupay query rsp: %s %s", response.status_code, response.text)

    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = str(data['orderlist'][0]['ordernumber'])
        total_fee = float(data['orderlist'][0]['money']) / 100.0
        pay_msg = unicode(data['orderlist'][0]['orderstatus'])

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == '1' and pay_msg == u'已支付':

            check_channel_order(pay_id, total_fee, app_id)

            _LOGGER.info('huifupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
            print("order process successfully. %s" % pay_order.id)
    else:
        _LOGGER.warn('huifupay data error, status_code: %s', response.status_code)
